package cn.hwadee.muying.controller;

import cn.hwadee.muying.commons.base.BaseController;
import cn.hwadee.muying.commons.constant.ConstantRole;
import cn.hwadee.muying.commons.jqgrid.GridResult;
import cn.hwadee.muying.commons.page.MyPage;
import cn.hwadee.muying.commons.utils.DateTools;
import cn.hwadee.muying.dto.Worker;
import cn.hwadee.muying.entity.Comment;
import cn.hwadee.muying.entity.Consult;
import cn.hwadee.muying.entity.Contract;
import cn.hwadee.muying.entity.User;
import cn.hwadee.muying.enums.Education;
import cn.hwadee.muying.enums.Level;
import cn.hwadee.muying.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.beetl.ext.fn.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mankind on 2018/8/13.
 */


@Controller
public class FrontController extends BaseController {

    @Autowired
    private ConsultService consultService;
    @Autowired
    private WorkerService workerService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationService orgService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private RecomendService recomendService;
    @Autowired
    private ClientService clientService;
    /**
     * 前台登录入口
     * @return
     */
    @RequestMapping(value = {"/login.html"})
    public String login(){
        return "/front/login";
    }


    /**
     * 注册界面入口
     * @return
     */
    @RequestMapping(value = {"/register.html"})
    public String register(){
        return "/front/register";
    }


    /**
     * 前台主界面入口
     * @return
     */
    @RequestMapping(value = {"/main.html"})
    public String main(){
        return "/front/main";
    }
    /**
     * 前台介绍界面入口
     * @return
     */
    @RequestMapping(value = {"/introduction.html"})
    public String introduction(){
        return "/front/introduction";
    }


    /**
     * 前台育婴师界面入口
     * @return
     */
    @RequestMapping(value = {"/careBaby.html"})
    public String careBaby(Model model,Integer curr, Integer limit,
    String city,String hometown,Long orgId,Long levelId,Long education,String experience,String age,String salary) throws Exception{
        model.addAttribute("age", age);
        model.addAttribute("experience", experience);
        model.addAttribute("salary", salary);
        model.addAttribute("city",city);
        model.addAttribute("hometown",hometown);
        model.addAttribute("orgId",orgId);
        model.addAttribute("educationId" ,education);
        model.addAttribute("levelId",levelId);
        if(curr==null&&limit==null){
            curr=1;
            limit=15;
        }
        if(StringUtils.isNotEmpty(city)){
            String[] temp=city.split("/");
            for(String str:temp){
                if(str.contains("市")){
                    city=str.substring(0,str.length()-1);
                }
            }
        }
        if(StringUtils.isNotEmpty(hometown)){
            hometown=hometown.split("/")[0];//只获取省份
        }
        Integer startExperience=null,endExperience=null,startAge=null,endAge=null,startSalary=null,endSalary=null;
        if(StringUtils.isNotEmpty(experience)){
            if(experience.contains("/")){
                startExperience=Integer.parseInt(experience.split("/")[0]);
                endExperience=Integer.parseInt(experience.split("/")[1]);
            }else{
                startExperience=Integer.parseInt(experience);
            }
        }
        if(StringUtils.isNotEmpty(age)){
            if(age.contains("/")){
                startAge=Integer.parseInt(age.split("/")[0]);
                endAge=Integer.parseInt(age.split("/")[1]);
            }else{
                startAge=Integer.parseInt(age);
            }
        }
        if(StringUtils.isNotEmpty(salary)){
            if(salary.contains("/")){
                startSalary=Integer.parseInt(salary.split("/")[0]);
                endSalary=Integer.parseInt(salary.split("/")[1]);
            }else{
                startSalary=Integer.parseInt(salary);
            }
        }

        MyPage<Worker> page = new MyPage<Worker>(curr, limit);
        page = workerService.frontList(page,city,hometown,orgId,levelId,education,startExperience,endExperience,startAge,endAge,startSalary,endSalary);

        model.addAttribute("orgs",orgService.selectAll());
        model.addAttribute("levels", Level.values());
        model.addAttribute("educations", Education.values());
        model.addAttribute("count",page.getTotal());
        model.addAttribute("curr",curr);
        model.addAttribute("workers",page.getRecords());
        return "/front/careBaby";
    }

    /**
     * 前台合同界面入口
     * @return
     */
    @RequestMapping(value = {"/myContract.html"})
    public String contract(Model model){
        User cUser=getCurrentUser();
        model.addAttribute("contracts",contractService.selectByUserId(cUser.getId()));
        return "/front/myContract";
    }


    /**
     * 前台个人中心界面入口
     * @return
     */
    @RequestMapping(value = {"/personCenter.html"})
    public String personCenter(Model model){
        model.addAttribute("client",clientService.selectByUserId(getCurrentUser().getId()));
        return "/front/personCenter";
    }

    /**
     * 前台育婴师信息界面入口
     * @return
     */
    @RequestMapping(value = {"/individualInfo.html"})
    public String individualInfo(Model model,Long workerId){
        model.addAttribute("worker",workerService.selectById(workerId));
        model.addAttribute("comments",commentService.selectFrontList(workerId));
        model.addAttribute("recommends",recomendService.selectRecommendList(workerId));
        return "/front/individualInfo";
    }




    @RequestMapping(value = "/front/consult", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> delete(Consult consult){
        Map<String,Object> result = new HashMap();
        if(StringUtils.isEmpty(consult.getAddress())){
            result.put("status",500);
            result.put("msg","请填写地址");
        }
        else if(StringUtils.isEmpty(consult.getAddress())){
            result.put("status",500);
            result.put("msg","请填写手机号");
        }
        else{
            try {
                User cUser=getCurrentUser();
                if(cUser!=null){
                    consult.setUserId(cUser.getId());
                }
                consultService.insert(consult);
                result.put("status",200);
                result.put("msg","咨询成功,请耐心等待客服电话~");
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg","咨询失败,请重试~");
            }
        }
        return result;
    }

    @RequestMapping(value = "/front/getWorkDay", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getWorkDay(String strStartDate,String strEndDate){
        Map<String,Object> result = new HashMap();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate=null;
        Date endDate = null;

        try {
            startDate=df.parse(strStartDate);
            endDate = df.parse(strEndDate);
        } catch (ParseException e) {
            result.put("msg","非法的日期格式,无法进行转换");
            result.put("code",500);
            e.printStackTrace();
        }
        result.put("code",200);
        result.put("days", DateTools.getDays(startDate,endDate));
        return result;
    }

    @RequestMapping(value = "/front/order", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> order(Contract contract){
        Map<String,Object> result = new HashMap();
        try{
            Worker nurseryTeacher=workerService.selectById(contract.getNurseryTeacherId());
            if(nurseryTeacher.getFree()==false){//如果育婴师已经被签约,那么拒绝预约
                result.put("status",500);
                result.put("msg","该育婴师已被预约!");
                return result;
            }
            User user=getCurrentUser();
            user.setOrgId(nurseryTeacher.getOrgId());//用户下完合同订单后,将用户的机构改为对应育婴师的机构
            userService.updateById(user);
            //随机分配一个育婴顾问
            Worker nurseryConsultant=workerService.selectConsultantByOrgIdRandomly();
            if (nurseryConsultant!=null){
                contract.setNurseryConsultantId(nurseryConsultant.getId());
                nurseryConsultant.setFree(false);
                workerService.updateById(nurseryConsultant);
            }
            //将对应的育婴师和育婴顾问的状态改为忙碌
            if(nurseryTeacher!=null){
                nurseryTeacher.setFree(false);
                workerService.updateById(nurseryTeacher);
            }
            contract.setStatus(true);
            contractService.insert(contract);
            result.put("status",200);
            result.put("msg","预约成功!");
        }catch (Exception e){
            result.put("status",500);
            result.put("msg","预约失败,请重试或联系管理员!");
        }
        return result;
    }

    @RequestMapping(value = "/front/comment", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> comment(Comment comment){
        Map<String,Object> result = new HashMap();
        try{
            User user=userService.selectById(comment.getWorkerId());
            if(user!=null){
                comment.setOrgId(user.getOrgId());
            }
            commentService.insert(comment);
            result.put("status",200);
            result.put("msg","评价成功!");
        }catch (Exception e){
            result.put("status",500);
            result.put("msg","评价失败,请重试或联系管理员!");
        }
        return result;
    }

}
